package com.hzx.service;

import com.hzx.OrderTable;
import com.hzx.clients.TimeClient;
import com.hzx.sender.KafkaSender;
import com.hzx.util.RedisUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SeckillService {
    @Autowired
    RedisUtil redisUtil;

    @Autowired
    TimeClient timeClient;

    @Autowired
    KafkaSender kafkaSender;

    /**
     * @param aId 活动ID
     * @param uId 用户ID
     * @return -1：商品不存在或者已经抢购完毕；-2：不在抢购时间；-3：抢晚了；-4:已经参加过抢购;1：抢购成功
     */
    public int seckill(int aId, int uId) {
        //这一步比较慢？为啥呢？
        Date startTime = (Date) redisUtil.get("time" + aId);
        if (startTime == null) return -1;
        if (timeClient.getTime().before(startTime)) return -2;
        if (redisUtil.get(aId + "&&" + uId) != null) return -4;
        Object keyWord = redisUtil.lPop("aid" + aId);

        //记录用户已经参加过抢购
        redisUtil.set(aId + "&&" + uId, keyWord != null);

        if (keyWord == null) return -3;

        addQueue(new OrderTable(aId, uId, keyWord.toString()));
        return 1;
    }

    @Async
    public void addQueue(OrderTable orderTable) {
        kafkaSender.sendMessage("orderTopic", orderTable);
    }
}
